import 'dart:developer';

import 'package:flutter/services.dart';
import 'package:lighthouse/pages/me/forget_password.dart';

import '../../index.dart';

//  强
const strong = r"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,18}$";
//  中
const middle =
    r"^(?=.{8,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$";
//  弱
const weak = r"(?=.{8,}).*";

class ForgetPasswordsNextPage extends StatefulWidget {
  Params params;

  ForgetPasswordsNextPage({Key? key, required this.params}) : super(key: key);

  @override
  State createState() =>
      _ForgetPasswordsNextState(this.params);
}

class _ForgetPasswordsNextState extends State<ForgetPasswordsNextPage> {
  String _name = '';
  String _phone = '';

  _ForgetPasswordsNextState(Params params) {
    _name = params.username;
    _phone = params.phone;
  }

  //表单状态
  final _formKey = GlobalKey<FormState>();

  //焦点
  final FocusNode _focusNewPas = FocusNode();
  final FocusNode _focusNewPass = FocusNode();

  //输入框控制器
  final TextEditingController _newPasController = TextEditingController();
  final TextEditingController _newPassController = TextEditingController();

  bool _isNewPas = false;
  bool _isNewPass = false;
  int _strong = 0;
  bool isConsecutive = false;

  @override
  void initState() {
    // TODO: implement initState

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var darkModel = Provider.of<DarkModel>(context);
    return GlobalStyle(
      child: BackgroundStyleWidget(
        child: Scaffold(
            backgroundColor: Colors.transparent,
            appBar: AppBar(
              leading: IconButton(
                icon: Image.asset('images/common_left.png',
                    width: 16, height: 16),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              title: const Text('忘记密码'),
              centerTitle: true,
              backgroundColor: Colors.transparent,
              systemOverlayStyle: darkModel.isDark(context)
                  ? SystemUiOverlayStyle.light
                  : SystemUiOverlayStyle.dark,
            ),
            body: _bodyView()),
      ),
    );
  }

  Widget _bodyView() {
    return SingleChildScrollView(
      child: Container(
          padding: const EdgeInsets.all(16),
          child: Column(
            children: [
              Container(
                width: double.infinity,
                padding: EdgeInsets.only(top: 14, bottom: 30),
                child: Text('重置密码用户 $_name',
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(
                        color: Theme.of(context).colorScheme.onPrimary)),
              ),
              _inputView('me_password', _newPasController, false, '请输入新密码',
                  (value) {

                //验证是否包含特殊字符
                bool isHaveSpecialCharacters(String input) {
                  final reg = RegExp(r'[`~!@#$%^&*()_+=|;:(){}'',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？-]');
                  return reg.hasMatch(input);
                }

                setState(() {
                  if (RegExp(weak).firstMatch(value) != null) {
                    _strong = 1;
                  }
                  if (RegExp(middle).firstMatch(value) != null) {
                    _strong = 2;
                  }
                  if (RegExp(strong).firstMatch(value) != null && isHaveSpecialCharacters(value) ) {
                    _strong = 3;
                  }
                  if (value.trim().length < 8) {
                    _strong = 0;
                  }
                  _padsCode(value);
                });
              }),
              SizedBox(height: 6),
              _colorList(_strong),
              SizedBox(height: 20),
              _inputView('me_password', _newPassController, false, '请输入新密码',
                  (value) {}),
              const SizedBox(height: 30),
              SizedBox(
                width: double.infinity,
                child: CommonButton.elevatedButton(context, text: "确定",
                    onPressed: () {
                  if (!_newPasController.text.isNotEmpty ||
                      !_newPassController.text.isNotEmpty) {
                    showToast("请填写密码");
                    return;
                  }
                  // if (isConsecutive) {
                  //   showToast("密码格式错误");
                  //   return;
                  // }
                  if (_newPasController.text != _newPassController.text) {
                    showToast('两次输入的密码不一致');
                    return;
                  }
                  if (_strong < 2) {
                    showToast('密码强度太弱');
                    return;
                  }
                  _submitAjax();
                }),
              )
            ],
          )),
    );
  }

  /// 验证密码格式
  void _padsCode(value) {
    List<int> valueCodes = value!.codeUnits;
    for (int i = 0; i < valueCodes.length - 2; i++) {
      //大于等于0且小于等于9 或 大于等于A小于等于Z 或大于等于a小于等于z
      if ((valueCodes[i] >= 48 && valueCodes[i] <= 57) ||
          (valueCodes[i] >= 65 && valueCodes[i] <= 90) ||
          (valueCodes[i] >= 97 && valueCodes[i] <= 122)) {
        //abc or 123
        if (valueCodes[i + 2] - valueCodes[i + 1] == 1 &&
            valueCodes[i + 1] - valueCodes[i] == 1) {
          isConsecutive = true;
          break;
          //aaa or 111
        } else if (valueCodes[i + 2] == valueCodes[i + 1] &&
            valueCodes[i + 1] == valueCodes[i]) {
          isConsecutive = true;
          break;
        }
      }
    }
  }

  /// 密码强弱
  Widget _colorList(strong) {
    if (strong == 1) {
      return Row(
        children: [
          const SizedBox(width: 12),
          _strength('弱', _color(1)),
          const SizedBox(width: 10),
          _strength('中', _color(0)),
          const SizedBox(width: 10),
          _strength('强', _color(0)),
        ],
      );
    }
    if (strong == 2) {
      return Row(
        children: [
          const SizedBox(width: 12),
          _strength('弱', _color(2)),
          const SizedBox(width: 10),
          _strength('中', _color(2)),
          const SizedBox(width: 10),
          _strength('强', _color(0)),
        ],
      );
    }
    if (strong == 3) {
      return Row(
        children: [
          const SizedBox(width: 12),
          _strength('弱', _color(3)),
          const SizedBox(width: 10),
          _strength('中', _color(3)),
          const SizedBox(width: 10),
          _strength('强', _color(3)),
        ],
      );
    }
    return Row(
      children: [
        const SizedBox(width: 12),
        _strength('弱', _color(0)),
        const SizedBox(width: 10),
        _strength('中', _color(0)),
        const SizedBox(width: 10),
        _strength('强', _color(0)),
      ],
    );
  }

  /// 密码强度
  /// name 文本
  /// state 状态
  Widget _strength(name, colors) {
    return Row(
      children: [
        Container(
          width: 66,
          height: 4,
          decoration: BoxDecoration(
            gradient: LinearGradient(
                //渐变位置
                begin: Alignment.bottomLeft, //右上
                end: Alignment.topRight, //左下
                stops: [0.0, 1.0], //[渐变起始点, 渐变结束点]
                //渐变颜色[始点颜色, 结束颜色]
                colors: colors),
            borderRadius: BorderRadius.circular((12)),
          ),
        ),
        SizedBox(width: 10),
        Container(
          width: 18,
          height: 18,
          alignment: Alignment.center,
          child: Text(name, style: TextStyle(color: Colors.white, fontSize: 9)),
          decoration: BoxDecoration(
            gradient: LinearGradient(
                //渐变位置
                begin: Alignment.topLeft, //右上
                end: Alignment.bottomLeft, //左下
                stops: [0.0, 1.0], //[渐变起始点, 渐变结束点]
                //渐变颜色[始点颜色, 结束颜色]
                colors: colors),
            borderRadius: BorderRadius.circular((12)),
          ),
        )
      ],
    );
  }

  /// 密码强弱
  List<Color> _color(value) {
    if (value == 1) {
      return const [
        Color.fromRGBO(255, 165, 168, 1),
        Color.fromRGBO(249, 63, 69, 1)
      ];
    }
    if (value == 2) {
      return const [
        Color.fromRGBO(83, 154, 255, 1),
        Color.fromRGBO(3, 48, 255, 1)
      ];
    }
    if (value == 3) {
      return const [
        Color.fromRGBO(83, 255, 214, 1),
        Color.fromRGBO(0, 177, 135, 1)
      ];
    }
    return const [
      Color.fromRGBO(203, 210, 217, 1),
      Color.fromRGBO(135, 135, 135, 1)
    ];
  }

  /// 输入框
  /// image 图标地址
  /// controller控制器
  /// obscure 是否为密码框
  /// name输入框名称
  /// fn回调
  Widget _inputView(image, controller, obscure, name, fn) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.only(left: 10, top: 0, right: 10, bottom: 0),
      decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.background,
          borderRadius: BorderRadius.circular(8.0),
          boxShadow: [
            BoxShadow(
                color: Theme.of(context).colorScheme.onSurface,
                blurRadius: 6.67,
                spreadRadius: 0.33)
          ]),
      child: Row(
        children: [
          Image.asset('images/$image.png', width: 20, height: 20),
          const SizedBox(width: 10),
          Flexible(
              child: TextField(
            controller: controller,
            obscureText: obscure,
            decoration: InputDecoration(
              contentPadding:
                  const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
              hintText: name,
              border: const OutlineInputBorder(borderSide: BorderSide.none),
            ),
            onChanged: (value) {
              fn(value);
            },
          ))
        ],
      ),
    );
  }

  ///修改密码
  void _submitAjax() async {
    showLoading(context);
    try {
      ResponseData responseData = await Api(context)
          .postPasswordLoginCode(_phone, _newPassController.text);
      Navigator.pop(context);
      if (responseData.success) {
        showToast("修改成功");
        Navigator.popUntil(context, ModalRoute.withName("login"));
      }
    } catch (e) {
      //登录失败则提示
      Navigator.pop(context);
      showToast(S.of(context).networkError);
    }
  }
}
